<template>
  <view class="classify">
    <view class="">
      <view class="padding">
        <my-newsearch></my-newsearch>
        <!-- <my-search></my-search> -->
      </view>
      <view class="all_area">
        <view class="left_area">
          <!-- 一级分类 -->
          <scroll-view
            class="scroll_left"
            scroll-y="true"
            :scroll-top="scrollTop"
          >
            <view
              class="sign_second flex-center"
              :class="{ active_text: secondIndex == index }"
              v-for="(item, index) in first_list"
              :key="item.id"
              @click="toggleTab(index)"
            >
              <text>{{ item.title | hideTitle }}</text>
            </view>
          </scroll-view>
        </view>
        <view class="right_area">
          <view class="right_top">
            <!-- 二级分类 -->
            <view class="tab_box" v-if="open == false">
              <u-tabs
                class="row_tabs"
                :is-scroll="true"
                :list="second_list"
                name="title"
                :current="current"
                @change="change"
                :show-bar="false"
                :addBorder="false"
                active-color="#40AE36"
                bg-color="none"
              ></u-tabs>
            </view>

            <view
              v-else
              class="over_box"
              :style="cssVars"
              :class="[open == false ? '' : 'new_hig']"
            >
              <view
                class="new_block"
                v-for="(item, index) in second_list"
                :key="index"
                :class="{ active: currentClass == index }"
                @click="selectSecond(item.id, index)"
              >
                {{ item.title | hideTitle1 }}
              </view>
            </view>
            <u-icon
              v-if="open"
              class="icon_down"
              style="margin-left: 24rpx"
              name="arrow-up"
              @click="down()"
            ></u-icon>
            <u-icon
              v-else
              class="icon_down"
              name="arrow-down"
              @click="down()"
            ></u-icon>
          </view>

          <view class="right_content" :style="{ marginTop: temp + 'rpx' }">
            <scroll-view scroll-y="true" class="all_good_height">
              <view
                v-for="(item, index) in goods_list"
                :key="index"
                class="sign_good my_listcol"
              >
                <view class="list">
                  <view class="flex info" @click="detailPage(index, item.id)">
                    <image
                      class="photo"
                      :src="item.img"
                      mode="aspectFit"
                    ></image>
                    <view class="desc">
                      <view class="list_name">
                        <text class="name">{{ item.name }}</text>
                        <text class="des" v-if="item.spu.length == 1">{{
                          item.spu[0].describe || ""
                        }}</text>
                        <!-- 收藏的星星 -->
                        <!-- <text class="custom-icon custom-icon-xingxing" v-else style="color:orange"></text> -->
                      </view>
                      <view class="tag flex wrap flex_col_center">
                        <text
                          v-for="(i, index) in item.datum"
                          :key="index"
                          class="red_tag"
                          >{{ i.title }}</text
                        >
                        <text v-if="item.datum_activity" class="yellow_tag">{{
                          item.datum_activity
                        }}</text>
                      </view>
                      <view class="inventory">
                        <text v-if="item.minimum > 0"
                          >起订量：{{ item.minimum }}</text
                        >
                        <text v-if="item.designated_inventory > 0"
                          >库存：{{ item.inventory_left }}</text
                        >
                      </view>
                       <view class="price_top">
                        <text v-if="canshowprice" class="red_font ten"
                          >{{ item.showPrice }}
                          <text
                            v-if="
                              item.spu.length == 1 &&
                              item.spu[0].current_price == 0
                            "
                            style="font-size: 20rpx"
                          >
                            /{{ item.spu[0].unit }}</text
                          >
                        </text>
                        <text v-else></text>
                        <!-- <view class="tag_box" v-if="item.spu.length > 1">
                          <image
                            @click.stop="showCart(index)"
                            class="addcartIcon"
                            src="/static/image/addcart.svg"
                            mode=""
                          ></image>
                          <text v-if="item.willBuyNum > 0" class="tag">{{
                            item.willBuyNum
                          }}</text>
                        </view> -->
                        <!-- <my-stepper v-else :val="item.willBuyNum" :min="item.minimum"
													:limit="item.designated_inventory" :inventory="item.inventory_left"
													:index="index" @plus="addAction" @minus="subAction" @showKey="
														$refs.keyboard.open(
															item.is_standard,
															index,
															item.minimum,
															item.inventory_left,
															item.designated_inventory
														)
													">
												</my-stepper> -->
                      </view>
                      <my-stepper
                        class="stepper_btn"
                        :val="item.willBuyNum"
                        :min="item.minimum"
                        :limit="item.designated_inventory"
                        :inventory="item.inventory_left"
                        :index="index"
                        @plus="addAction(item, index, $event)"
                        @minus="subAction"
                        @showKey="
                          $refs.keyboard.open(
                            item.is_standard,
                            index,
                            item.minimum,
                            item.inventory_left,
                            item.designated_inventory
                          )
                        "
                      >
                      </my-stepper>
                    </view>
                  </view>
                </view>
              </view>
            </scroll-view>

            <view v-if="toNext" @click="toNextAction" class="tonext flex-center"
              >{{ bottomText }}
              <text style="color: red; margin-left: 10rpx">{{
                next_category_name
              }}</text>
            </view>
            <view class="nodata" v-if="goods_list.length == 0">
              <image :src="nodataImg" mode="aspectFit"></image>
              <view>该分类暂时还没有商品~</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <my-keyboard ref="keyboard" @confirm="inputPrice"></my-keyboard>
    <my-addcart
      ref="minicart"
      @tabBarTag="changeTabBarTag"
      :canshowprice="canshowprice"
    ></my-addcart>
    <my-tabar ref="tabar" current="1"></my-tabar>
  </view>
</template>

<script>
import { $https } from "@/static/js/request.js";
import MixinShowprice from "@/static/js/mixinshowprice.js";
export default {
  data() {
    return {
      nodataImg: getApp().globalData.nodataImg,
      loginVolid: null, //是否强制登录
      logo: "",
      showLogo: 0,
      page: 1,
      count: 0,
      current: 0,
      scrollTop: 0,
      first_list: [],
      second_list: [],
      secondIndex: 0,
      goods_list: [],
      pid: null, //当前一级分类id
      category_id: null, //当前二级分类id
      next_category_id: null, //下个二级分类id
      next_category_name: "", //下个二级分类
      toNext: false,
      bottomText: "点击加载",
      indexNavid: null, //从首页导航或者banner过来
      flag: true, //onshow是否刷新
      currentClass: 0,
      open: false,
      // #ifdef APP-PLUS
      temp: 100,
      // #endif

      // #ifdef H5 || MP-WEIXIN
      temp: 90,
      // #endif
    };
  },
  mixins: [MixinShowprice],

  onReady() {
    getApp().setTitle();
  },

  onLoad(options) {
    this.indexNavid = options.navid;
    if (options.navid) {
      this.pid = options.navid;
    }
    this.loginVolid = !Boolean(
      uni.getStorageSync("loginVolid").is_login_category
    );
  },

  onShow() {
    //先由emit触发，再执行onshow
    uni.$once("updateclassify", (res) => {
      this.flag = false;
    });
    if (this.flag) {
      this.goods_list = [];
      var params = {};
      if (this.pid) {
        Object.assign(params, {
          pid: this.pid,
        });
        this.currentClass = 0;
        this.current = 0;
      }
      if (this.category_id) {
        Object.assign(params, {
          category_id: this.category_id,
        });
      }
      this.getData(1, params, this.secondIndex);
    }
    this.flag = true;
  },
  computed: {
    cssVars() {
      return {
        "--second_list_length": this.second_list.length,
      };
    },
  },
  filters: {
    hideTitle(value) {
      if (!value) return "";
      return value.slice(0, 4);
    },
    hideTitle1(value) {
      if (!value) return "";
      return value.slice(0, 5);
    },
  },
  methods: {
    getData(page, prop, index = 1) {
      this.toNext = false;
      var params = {
        page: page,
        size: 15,
      };
      if (prop) {
        Object.assign(params, prop);
      }
      //
      if (!params.category_id) delete params.category_id;
      $https(
        "GET",
        "category",
        params,
        (res) => {
          let data = res.data.data;
          //是否显示logo
          uni.setStorageSync("showLogo", data.auto_watermark);
          uni.setStorageSync("logo", data.site_logo);
          this.showLogo = data.auto_watermark;
          this.logo = data.site_logo;
          // 设置商品总数
          this.count = data.count;
          // 设置一级分类，当一级分类为0时，赋值给first_list，否则跳过;并且将商品制空
          if (this.first_list.length == 0) {
            this.first_list = res.data.data.first_list;
          }
          // 设置二级分类
          this.second_list = data.second_list;
          // 设置展示的商品名称;处理价格规格sku
          let goods_list = this.changePrice(data.goods_list);
          this.goods_list = this.goods_list.concat(goods_list);

          /**
           * 设置商品最后的文字展示效果
           * 判断条件：
           * 	1、商品数量大于0
           * 	2、当前商品数量是否低于总数量
           * 	3、当前secondIndex低于该二级分类总数 - 1
           * 		3.1、如果是最后一个二级分类时，应展示没有更多了
           */
          if (
            this.goods_list.length > 0 &&
            this.goods_list.length == this.count &&
            this.secondIndex < this.second_list - 1
          ) {
            this.toNext = true;
            this.bottomText = "点击加载";
          } else {
            this.toNext = true;
            this.bottomText = "没有更多了";
            this.next_category_name = "";
            this.next_category_id = null;
          }
          //如果有这个id，说明是首页导航或者banner来的。默认选中那个分类
          if (this.indexNavid) {
            this.changeFirstCurrent(this.indexNavid);
          }

          /**
           * 获取下个二级分类的分类名、二级分类id
           */
          let next = this.second_list[index];
          this.next_category_name = next ? next.title : "";
          this.next_category_id = next ? next.id : null;
          /**
           * 获取一级分类id
           * 刚进入分类页面时，需将一级分类的id赋值给pid，后续操作后pid修改
           */
          if (!this.pid && this.first_list.length) {
            this.pid = this.first_list[0].id;
            this.category_id = this.first_list[0].selfNext[0].id;
          } else {
            let cate_id = this.first_list.filter((item) => item.id == this.pid);
            this.category_id = cate_id[0].selfNext[this.current].id;
          } 
          if (this.pid) {
            this.secondIndex = this.first_list.findIndex((item) => {
              return item.id == this.pid;
            });
          }

          this.page = page;
          this.$refs.tabar.changetag(res.data.data.all_cart_num);
        },
        this.loginVolid
      );
    },

    //处理价格规格sku
    changePrice(data) {
      var array = JSON.parse(JSON.stringify(data));
      for (let i in array) {
        //算出价格范围
        if (array[i].spu.length > 1) {
          var min, max;
          min = array[i].spu[0].market_price;
          if (array[i].spu[1].market_price < min) {
            max = Number(array[i].spu[0].market_price);
            min = Number(array[i].spu[1].market_price);
          } else {
            max = Number(array[i].spu[1].market_price);
            min = Number(array[i].spu[0].market_price);
          }
          for (let y in array[i].spu) {
            if (Number(array[i].spu[y].market_price) < min) {
              min = Number(array[i].spu[y].market_price);
            } else if (Number(array[i].spu[y].market_price) > max) {
              max = Number(array[i].spu[y].market_price);
            }
          }
          let bol1 = array[i].spu.some((e) => {
            return e.current_price == 1;
          });
          let bol2 = array[i].spu.every((e) => {
            return e.current_price == 1;
          });
          let arr = [];
          array[i].spu.forEach((e) => {
            if (e.current_price != 1) {
              arr.push(e.market_price);
            }
          });
          let maxs = Math.max(...arr);
          let mins = Math.min(...arr);
          // console.log(max,min);
          if (bol2) {
            array[i].showPrice = "时价";
          } else if (bol1) {
            array[i].showPrice = `时价~${maxs.toFixed(2)}`;
          } else {
            array[i].showPrice = `￥${mins.toFixed(2)}~${maxs.toFixed(2)}`;
          }
          // array[i].showPrice = `￥${min.toFixed(2)}~${max.toFixed(2)}`;
        } else if (array[i].spu.length == 1) {
          if (array[i].spu[0].activity_price) {
            //活动价
            array[i].showPrice = "￥" + array[i].spu[0].activity_price;
          } else if (array[i].spu[0].current_price == 1) {
            //是时价
            array[i].showPrice = "时价";
          } else {
            array[i].showPrice = "￥" + array[i].spu[0].market_price;
          }
          //只有一个规格时显示起订量、库存
          array[i].minimum = array[i].spu[0].minimum;
          array[i].designated_inventory = array[i].spu[0].inventory_hd
            ? 11
            : array[i].spu[0].designated_inventory;
          array[i].inventory_left =
            array[i].spu[0].inventory_hd || array[i].spu[0].inventory_left;
        }
        array[i].willBuyNum = array[i].num_cart_count;
      }
      return array;
    },

    // 点击二级分类时根据获取到的二级分类下标获取二级分类id并调用获取商品接口
    change(index) {
      // 将商品列表制空
      this.goods_list = [];
      // 修改二级分类选中的样式，赋值当前选中的二级分类下标
      this.currentClass = index;
      this.current = index;
      // 将商品下面的提示语隐藏
      this.toNext = false;
      // 根据pid匹配一级分类的二级分类列表
      let category_list = this.first_list.filter(
        (item) => item.id == this.pid
      )[0];
      // 获取二级分类id
      let category_id = category_list.selfNext[index]
        ? category_list.selfNext[index].id
        : null;
      this.category_id = category_id;
      this.getData(
        1,
        {
          pid: this.pid,
          category_id: category_id,
        },
        index + 1
      );
    },
    //点击一级列表
    toggleTab(index) {
      this.secondIndex = index;
      this.goods_list = [];
      this.currentClass = 0;
      this.current = 0;
      this.pid = this.first_list[index].id;
      this.category_id = this.first_list[index].selfNext[0].id; //重设二级id
      this.toNext = false;
      this.getData(1, {
        pid: this.pid,
        category_id: this.category_id,
      });
    },

    down() {
      this.open = !this.open;
      if (this.open == true) {
        let count = 0;
        for (let i = 1; i <= this.second_list.length; i++) {
          if (i % 3 == 0) {
            count++;
          }
        }
        this.temp = count * 90 || 90;
      } else {
        // #ifdef APP-PLUS
        this.temp = 100;
        // #endif

        // #ifdef H5 || MP-WEIXIN
        this.temp = 90;
        // #endif
      }
    },

    /**
     * 点击二级分类时函数
     * id: 二级分类id
     * index: 展示的二级分类下标
     */
    selectSecond(id, index) {
      // 将商品列表制空
      this.goods_list = [];
      // 修改二级分类选中的样式，赋值当前选中的二级分类下标
      this.currentClass = index;
      this.current = index;
      // 将商品下面的提示语隐藏
      this.toNext = false;
      this.change(index);
    },

    //＋
    addAction(item, index, data) {
      if (item.spu.length > 1) {
        this.showCart(index);
      } else {
        var index = data.index,
          min = data.min,
          limit = data.limit,
          inventory = data.inventory,
          val = data.value;
        if (val < min) {
          val = min;
        } else if (limit > 0 && val + 1 >= inventory) {
          //不能超过库存量
          val = inventory;
          uni.showToast({
            icon: "none",
            title: "库存不足",
          });
          return;
        } else {
          val++;
        }
        this.addToCart(
          this.goods_list[index].id,
          this.goods_list[index].spu[0].id,
          val.toFixed(2),
          index
        );
      }
    },
    //-
    subAction(data) {
      var index = data.index,
        min = data.min,
        inventory = data.inventory,
        val = data.value;

      if (val - 1 < min) {
        val = 0;
      } else {
        val--;
      }
      // this.goods_list[data.index].willBuyNum = val;
      this.addToCart(
        this.goods_list[index].id,
        this.goods_list[index].spu[0].id,
        val.toFixed(2),
        index
      );
    },
    //输入数量
    inputPrice(data) {
      var val = Number(data.value),
        index = data.index;
      this.addToCart(
        this.goods_list[index].id,
        this.goods_list[index].spu[0].id,
        val.toFixed(2),
        index
      );
    },
    addToCart(goodsId, spuId, num, index) {
      var options = {
        goods_id: goodsId,
        spu_id: spuId,
        num,
      };
      $https("POSTN", "changeCart", options, (res) => {
        if (res.data.errcode == 0) {
          this.goods_list[index].willBuyNum = Number(num);
          this.$refs.tabar.changetag(res.data.data.all_cart_num);
        } else {
          uni.showToast({
            title: res.data.errmsg,
            icon: "none",
          });
        }
      });
    },
    //跳到商品详情
    detailPage(index, id) {
      uni.navigateTo({
        url: `../../subindex/index/shopdetail?id=${id}`,
      });
    },
    //显示小购物车
    showCart(index) {
      var data = this.goods_list[index];
      this.$refs.minicart.open(data);
    },
    toNextAction() {
      let index = this.current + 1;
      // 如果有下级id，表示可点击。
      if (this.next_category_id) {
        this.selectSecond(this.next_category_id, index);
      }
    },
    //改变底部导航栏购物车tag
    changeTabBarTag(num) {
      this.$refs.tabar.changetag(num);
    },
    changeFirstCurrent(id) {
      for (let index in this.first_list) {
        if (this.first_list[index].id == id) {
          this.current = 0;
          this.indexNavid = null;
          return;
        }
      }
    },
    // 设置商品最后的文字展示效果
    setText() {},
  },
  onReachBottom() {
    var page = this.page;
    console.log(this.category_id)
    //如果请求到底就请求下一列表
    if (this.goods_list.length < this.count) {
      page++;
      this.getData(
        page,
        {
          pid: this.pid,
          category_id: this.category_id,
        },
        this.current + 1
      );
    } else {
      this.toNext = true;
      if (!this.next_category_id) {
        this.bottomText = "没有更多啦~";
      } else {
        this.bottomText = "点击加载";
      }
    }
  },
};
</script>

<style lang="scss">
/deep/.u-drawer {
  overflow: unset !important;
}

.classify {
  .all_area {
    display: flex;

    // margin-bottom:90rpx;
    .left_area {
      // height: calc(100vh - 90px - 128rpx);
      background: #e9e9e9;
      position: fixed;
      left: 0;
      // #ifndef MP-WEIXIN
      top: calc(var(--status-bar-height) + 121rpx);
      // #endif
      //#ifdef MP-WEIXIN
      top: 121rpx;
      // #endif
      bottom: 0;

      .scroll_left {
        width: 180rpx;
        height: calc(100vh - 98rpx - 130rpx - env(safe-area-inset-bottom));
      }

      .sign_second {
        height: 100rpx;
        padding: 0 8rpx;
        // line-height: 100rpx;
        font-size: 26rpx;
        border-bottom: 1px solid #d1d1d1;
        text-align: center;
      }

      .active_text {
        background: $white;
        font-weight: 600;
      }

      .active_text text {
        color: $dgreen;
      }

      .active_text::before {
        display: block;
        position: absolute;
        left: 0;
        width: 8rpx;
        height: 32rpx;
        // margin-top: 32rpx;
        background: $dgreen;
        content: "";
      }
    }

    .right_area {
      width: 100%;
      margin-left: 182rpx;
      // flex: 1;
      // border-top: 1px solid #d1d1d1;
      // height: calc(100vh - 98rpx - 130rpx);
      overflow: auto;
      // position: relative;
      display: flex;
      flex-direction: column;

      .right_top {
        position: fixed;
        //#ifndef MP-WEIXIN
        top: calc(var(--status-bar-height) + 121rpx);
        // #endif
        //#ifdef MP-WEIXIN
        top: 121rpx;
        // #endif
        left: 180rpx;
        right: 0;
        background: #f6f6f7;
        z-index: 2;
        display: flex;

        .choose_food {
          font-size: 32rpx;
          color: #191919;
          padding: 15rpx 16rpx;
        }
      }

      .right_content {
        flex: 1;
        overflow: auto;
        //#ifndef MP-WEIXIN
        // margin-top: calc(var(--status-bar-height) + 74rpx);
        // #endif
        //#ifdef MP-WEIXIN
        // margin-top: 74rpx;

        // #endif
        .tonext {
          height: 150rpx;
          font-size: 24rpx;
          color: #666;
        }

        // .all_good_height {
        // 	// height: calc(100vh - 50px - 130rpx);
        // }
        .nodata {
          margin-left: 270rpx;
        }

        .my_listcol {
          box-sizing: border-box;

          .list {
            // min-height: 200rpx;
            flex: 1;
            padding: 30rpx 0;
            margin: 0 30rpx;
            border-bottom: 1px solid #cccccc;
            display: flex;

            .info {
              flex-grow: 1;
              align-items: center;
              position: relative;

              .logo {
                width: 40rpx;
                height: 40rpx;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 1;
              }

              .photo {
                width: 120rpx;
                height: 120rpx;
                margin-right: 16rpx;
              }
            }

            .desc {
              // height: 100%;
              flex: 1;
              position: relative;

              // font-size: 20rpx;
              > view + view {
                margin-top: 4rpx;
              }

              .price_top {
                display: flex;
                justify-content: space-between;
                align-items: center;
                .ten{
                  font-size: 32rpx;
                }
                .tag {
                  position: absolute;
                  right: -20rpx;
                  top: -8rpx;
                  margin-top: -5px;
                  padding: 0 8rpx;
                  transform: scale(0.8);
                  height: 15px;
                  line-height: 15px;
                  border-radius: 15rpx;
                  text-align: center;
                  color: $white;
                  font-size: 20rpx;
                  background: #fa3534;
                }

                .addcartIcon {
                  width: 60rpx;
                  height: 60rpx;
                }
              }

              .list_name {
                .name {
                  font-size: 30rpx;
                  color: #333;
                  font-weight: bold;
                }

                .des {
                  flex: 1;
                  color: #666;
                  display: -webkit-box;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 1;
                  overflow: hidden;
                  // white-space: nowrap;
                  // overflow: hidden;
                  // text-overflow: ellipsis;
                  margin-top: 4rpx;
                  font-size: 24rpx;
                }
              }

              .red_tag {
                font-size: 24rpx;
                padding: 0 12rpx;
                background: red;
                margin-bottom: 6rpx;
              }

              .yellow_tag {
                font-size: 24rpx;
                padding: 0 12rpx;
                background: #ff9900;
                border-radius: 6rpx;
                color: #fff;
              }

              .inventory {
                color: #737373;
                font-size: 24rpx;

                > text + text {
                  margin-left: 20rpx;
                }
              }
            }

            .custom-icon-gouwu {
              color: $dgreen;
              font-size: 10px;
            }
          }
        }
      }
    }
  }
}

.over_box {
  width: 460rpx;
  display: grid;
  grid-template-rows: repeat(var(--second_list_length) / 3, 80rpx);
  grid-template-columns: repeat(3, 1fr);
  text-align: center;
  padding: 0 14rpx;
}

.tab_box {
  width: 88%;
  padding: 0 14rpx;
  // font-weight: bold;
}

.new_block {
  height: 80rpx;
  line-height: 80rpx;
  font-size: 26rpx;
}

.new_hig {
  height: auto !important;
}

.icon_down {
  height: 74rpx;
  line-height: 74rpx;
  padding-right: 28rpx;
  display: flex;
}

.active {
  color: $dgreen;
  font-weight: 600;
}
.stepper_btn {
  position: absolute;
  bottom: -20rpx;
  right: 0;
}
.ten {
  font-size: 24rpx;
}
/deep/.u-tab-item {
  font-size: 26rpx !important;
  width: 144rpx !important;
  padding: 0 !important;
}
</style>
